import { CategoriesData } from './itemsDataGetter';

const getCategoriesWithItems = (data: CategoriesData): string[] => {
  const categories: string[] = [];
  
  // 按照window.baseDS.categories的顺序来返回分类，保持YAML文件中定义的顺序
  if (window.baseDS && window.baseDS.categories && Array.isArray(window.baseDS.categories)) {
    // 使用baseDS中定义的顺序
    window.baseDS.categories.forEach((baseCat: { name: string }) => {
      const categoryName = baseCat.name;
      if (data[categoryName]) {
        let itemsNumber = 0;
        Object.keys(data[categoryName]).forEach((subcat: string) => {
          itemsNumber += data[categoryName][subcat].items.length;
        });
        if (itemsNumber > 0) {
          categories.push(categoryName);
        }
      }
    });
    
    // 处理可能存在于data中但不在baseDS.categories中的分类（以防万一）
    Object.keys(data).forEach((cat: string) => {
      if (!categories.includes(cat)) {
        let itemsNumber = 0;
        Object.keys(data[cat]).forEach((subcat: string) => {
          itemsNumber += data[cat][subcat].items.length;
        });
        if (itemsNumber > 0) {
          categories.push(cat);
        }
      }
    });
  } else {
    // 如果baseDS.categories不存在，使用原来的逻辑
    Object.keys(data).forEach((cat: string) => {
      let itemsNumber = 0;
      Object.keys(data[cat]).forEach((subcat: string) => {
        itemsNumber += data[cat][subcat].items.length;
      });
      if (itemsNumber > 0) {
        categories.push(cat);
      }
    });
  }
  
  return categories;
};

export default getCategoriesWithItems;
